﻿using MvvmCross.Core.ViewModels;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Sidvall.LogManager.UI.ViewModels
{
    public partial class UserConfigurationViewModel
    {
        #region PageTypes

        private Sidvall.Data.KeyValueCollection<string, Sidvall.LogManager.Data.PageType> _PageTypes;
        public Sidvall.Data.KeyValueCollection<string, Sidvall.LogManager.Data.PageType> PageTypes
        {
            get
            {
                if (_PageTypes == null)
                    this.PageTypes = Sidvall.Data.KeyValueManager.FromEnum<Sidvall.LogManager.Data.PageType>();
                return _PageTypes;
            }
            set
            {
                _PageTypes = value;
                RaisePropertyChanged("PageTypes");
            }
        }

        #endregion
        #region CanConnectToServer

        public bool CanConnectToServer
        {
            get
            {
                return Sidvall.LogManager.Security.SecurityManager.CanConnectToServer;
            }
        }

        #endregion
        #region TwoFactorProviders

        private Sidvall.Data.KeyValueCollection<string, Sidvall.Security.TwoFactorProvider> _TwoFactorProviders;
        public Sidvall.Data.KeyValueCollection<string, Sidvall.Security.TwoFactorProvider> TwoFactorProviders
        {
            get
            {
                if (_TwoFactorProviders == null)
                    this.TwoFactorProviders = Sidvall.Data.KeyValueManager.FromEnum<Sidvall.Security.TwoFactorProvider>();
                return _TwoFactorProviders;
            }
            set
            {
                _TwoFactorProviders = value;
                RaisePropertyChanged(nameof(TwoFactorProviders));
            }
        }

        #endregion

        // Commands
        #region ExportSettings

        public ICommand ExportSettingsCommand
        {
            get
            {
                return new MvxCommand(async () => await ExportSettingsAsync());
            }
        }
        public async Task ExportSettingsAsync()
        {
            Sidvall.LogManager.Net.Services.V1.UserConfiguration userConfiguration;
            string fileName, content;
            Task task = null;

            try
            {
                fileName = await Sidvall.UI.SystemContext.Current.DialogManager.SaveFileAsync();
                if (string.IsNullOrWhiteSpace(fileName))
                    return;
                userConfiguration = new Net.Services.V1.UserConfiguration();
                userConfiguration.Import(this.ActiveEntity, Sidvall.Data.CopySettings.FullCopyAll(Sidvall.Data.DataRowContextOption.None, null));
                content = Sidvall.Serialization.SerializerManager.Current.SerializeObject(userConfiguration);
                await Sidvall.SystemContext.Current.SystemStorageManager.WriteAllTextAsync(fileName, content);
            }
            catch (System.Exception ex)
            {
                task = Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync("Save Error", ex);
            }
            if (task != null)
                await task;
        }

        #endregion
        #region ImportSettings

        public ICommand ImportSettingsCommand
        {
            get
            {
                return new MvxCommand(async () => await ImportSettingsAsync());
            }
        }
        public async Task ImportSettingsAsync()
        {
            string fileName;
            string content;
            Task task = null;

            try
            {
                fileName = await Sidvall.UI.SystemContext.Current.DialogManager.OpenFileAsync("Text Files (*.txt)|*.txt|All Files (*.*)|*.*", "*.txt");
                if (string.IsNullOrWhiteSpace(fileName))
                    return;
                content = await Sidvall.SystemContext.Current.SystemStorageManager.ReadAllTextAsync(fileName);
                this.ActiveEntity = Sidvall.LogManager.UI.SystemContext.Current.LoadUserConfiguration(content);
                this.ActiveEntity = await Sidvall.LogManager.UI.SystemContext.Current.SaveUserConfigurationAsync(this.ActiveEntity, true);
            }
            catch (System.Exception ex)
            {
                task = Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync("Save Error", ex);
            }
            if (task != null)
                await task;
        }

        #endregion
        #region RefreshItems

        public ICommand RefreshItemsCommand
        {
            get
            {
                return new MvxCommand(async () => await RefreshItemsAsync());
            }
        }
        public async Task RefreshItemsAsync()
        {
            Task task = null;
            using (var busyManager = new Sidvall.Data.BusyManager(this))
            {
                try
                {
                    this.ActiveEntity = await Sidvall.LogManager.UI.SystemContext.Current.LoadUserConfigurationAsync();
                }
                catch (System.Exception ex)
                {
                    task = Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync("Save Error", ex);
                }
                if (task != null)
                    await task;
            }
        }

        #endregion
        #region ConnectToServer

        public ICommand ConnectToServerCommand
        {
            get
            {
                return new MvxCommand(async () => await ConnectToServerAsync());
            }
        }
        public async Task ConnectToServerAsync()
        {
            if (!this.CanConnectToServer)
                return;
            using (var busyManager = new Sidvall.Data.BusyManager(this))
            {
                try
                {
                    await Sidvall.LogManager.UI.SystemContext.Current.LoadServerInfoAsync(true, true);
                    await DoLoadAsync();
                }
                catch (System.Exception ex)
                {
                    await Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync("Export Error", ex);
                }
            }
        }

        #endregion

        // View model
        #region LoadItemAsync

        protected override Task<Entities.UserConfiguration> LoadItemAsync()
        {
            return Task.FromResult(Sidvall.LogManager.UI.SystemContext.Current.UserConfiguration);
        }

        #endregion
        #region SaveItemAsync

        protected override async Task<Entities.UserConfiguration> SaveItemAsync(Entities.UserConfiguration item)
        {
            return await Sidvall.LogManager.UI.SystemContext.Current.SaveUserConfigurationAsync(item, false);
        }

        #endregion
        #region StartAsync

        protected override async Task StartAsync()
        {
            await DoLoadAsync();
        }

        #endregion
    }
}
